import { reactive, readonly } from 'vue'
import { getSysParams } from '@/api/common'
import { data2Dict } from '@/utils'
import pageDictAPIs from '@/api/dict'

interface DictState {
  [key: string]: any;
}

/**
 * 系统参数dict存储 before
 */
const sysDictState = reactive<DictState>({
  // carInfo_driveNature: [],
})
// 避免外部直接更改state值
export const sysDict = new Proxy(sysDictState, {
  get: (target, propKey: string) => {
    return target[propKey].filter((it: any) => !it.disabled)
  },
})

export const sysDictOrigin = readonly(sysDictState)

export function useSysDict(codeList: string[], cb?: Function) {
  if (!codeList) return
  const missList: string[] = []
  codeList.forEach((code) => {
    // 防止重复掉API，没有初始化，并记录到mistlist
    if (!sysDictState[code]) {
      missList.push(code)
    }
  })

  if (missList.length == 0) {
    cb && cb(sysDictState)
    return sysDictState
  }

  getSysParams({ codeList: missList, includeDisabled: 1 }).then((res: any) => {
    const result = res.result
    if (result) {
      missList.forEach((it: string) => {
        const sysP = data2Dict(result[it])
        sysDictState[it] = sysP
      })
    }
  })
  return sysDictState
}

// 获取最新的值 更新系统参数{code}的值
export function dispacthSysDict(code: string) {
  if (!code) return
  getSysParams({ codeList: [code], includeDisabled: 1 }).then((res: any) => {
    const result = res.result
    if (result) {
      const sysP = data2Dict(result[code])
      sysDictState[code] = sysP
    }
  })
}
// end

/**
 * 页面固定参数dict存储 before
 */

const pageDictState = reactive<DictState>({
  // 'shortOrderDict': {}
}) as any
// 避免外部直接更改state值
export const pageDict = readonly(pageDictState)

export function usePageDict<T = any>(pageDictCode: string, cb?: Function, readCatch = true): T {
  let pageDict = pageDictState[pageDictCode]
  if (pageDict && readCatch) {
    cb && cb(pageDict)
  } else {
    // 去调API获取dict数据
    pageDictState[pageDictCode] = {}
    pageDictAPIs[pageDictCode]().then((res: any) => {
      if (res.code == 200) {
        const pageRes2Dict = {}
        const result = res.result
        for (const key in result) {
          pageRes2Dict[key] = data2Dict(result[key])
        }
        Object.assign(pageDictState[pageDictCode], pageRes2Dict)
        pageDict = pageDictState[pageDictCode]
        cb && cb(pageDict)
      }
    }).catch(() => {
      pageDictState[pageDictCode] = undefined
    })
  }
  return pageDictState[pageDictCode]
}
// end


// 清空函数
function clearPageDictState(state: DictState) {
  Object.keys(state).forEach(key => {
    delete state[key];
  });
}


// 退出清除所有dict数据
export function clearDict() {
  clearPageDictState(pageDictState);
  clearPageDictState(sysDictState);
}
